package com.hngy.xpq.zhinanzhen;

import androidx.appcompat.app.AppCompatActivity;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    ImageView image;  //指南针图片
    float currentDegree = 0f; //指南针图片转过的角度
    Mylistenner  mylistenner =new Mylistenner();
    SensorManager mSensorManager; //管理器

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        image = (ImageView)findViewById(R.id.image_znz);
        mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); //获取管理服务
    }


    @Override
    protected void onResume(){
        super.onResume();
        //注册监听器
        // mSensorManager.getOrientation();
        mSensorManager.registerListener(mylistenner
                , mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME);
    }

    //取消注册
    @Override
    protected void onPause(){
        mSensorManager.unregisterListener(mylistenner);
        super.onPause();
    }

    @Override
    protected void onStop(){
        mSensorManager.unregisterListener(mylistenner);
        super.onStop();

    }
    public  class Mylistenner implements SensorEventListener{
        //传感器值改变
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // TODO Auto-generated method stub

        }
        //精度改变
        @Override
        public void onSensorChanged(SensorEvent event) {
            // TODO Auto-generated method stub
            //获取触发event的传感器类型
            int sensorType = event.sensor.getType();

            switch(sensorType){
                case Sensor.TYPE_ORIENTATION:
                    float degree = event.values[0]; //获取z转过的角度
                    //穿件旋转动画
                    RotateAnimation ra = new RotateAnimation(currentDegree,-degree,Animation.RELATIVE_TO_SELF,0.5f
                            ,Animation.RELATIVE_TO_SELF,0.5f);
                    ra.setDuration(100);//动画持续时间
                    image.startAnimation(ra);
                    currentDegree = -degree;
                    break;

            }
        }
    }
}
